package com.yiyiooo.Abp.utils;

import android.app.ActivityManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.provider.Settings;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;

import static android.content.Context.ACTIVITY_SERVICE;
import static android.text.TextUtils.isEmpty;

public class SystemUtils {
    public static String getDeviceId(Context context) {
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {
            //IMEI（imei）
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if(android.os.Build.VERSION.SDK_INT <=29){
                try{
                    String imei = tm.getDeviceId();
                    if(!isEmpty(imei)){
                        deviceId.append("imei");
                        deviceId.append(imei);
//                Log.e("getDeviceId : ", deviceId.toString());
                        return deviceId.toString();
                    }
                }catch (Exception ex){
//                    throw ex;
                }
            }
            //序列号（sn）
            if(android.os.Build.VERSION.SDK_INT <=29){
                try{
                    String sn = tm.getSimSerialNumber();
                    if(!isEmpty(sn)){
                        deviceId.append("sn");
                        deviceId.append(sn);
//                Log.e("getDeviceId : ", deviceId.toString());
                        return deviceId.toString();
                    }
                }catch (Exception ex){
//                throw ex;
                }
            }
            //如果上面都没有， 则生成一个id：随机码
            try{
                String uuid = getUUID(context);
                if(!isEmpty(uuid)){
                    deviceId.append("id");
                    deviceId.append(uuid);
//                Log.e("getDeviceId : ", deviceId.toString());
                    return deviceId.toString();
                }
            }catch (Exception ex){
//                throw ex;
            }

        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID(context));
        }
//        Log.e("getDeviceId : ", deviceId.toString());
        return deviceId.toString();
    }
    /**
     * 得到安装唯一UUID 重装会发生变化
     */
    private static String getUUID(Context context) {
        return getInstallId(context);
    }

    private static String sID = null;
    private static final String INSTALLATION = "INSTALLATION";

    public synchronized static String getInstallId(Context context) {
        if (sID == null) {
            File installation = new File(context.getFilesDir(), INSTALLATION);
            try {
                if (!installation.exists())
                    writeInstallationFile(installation);
                sID = readInstallationFile(installation);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sID;
    }
    private static String readInstallationFile(File installation) throws IOException {
        RandomAccessFile f = new RandomAccessFile(installation, "r");
        byte[] bytes = new byte[(int) f.length()];
        f.readFully(bytes);
        f.close();
        return new String(bytes);
    }

    private static void writeInstallationFile(File installation) throws IOException {
        FileOutputStream out = new FileOutputStream(installation);
        String id = UUID.randomUUID().toString();
        out.write(id.getBytes());
        out.close();
    }

    // 获取手机号码
    private static Context mContext;
    private static TelephonyManager mTelephonyManager;
    private ConnectivityManager mConnMngr;
    private static SubscriptionManager mSubscriptionManager;
    public void RegisterMessage(Context context) {
        mContext = context;
        mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (mTelephonyManager == null) {
            throw new Error("telephony manager is null");
        }
        mConnMngr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        mSubscriptionManager = SubscriptionManager.from(mContext);
    }
    public String getMsisdn(int slotId) {//slotId 0为卡1 ，1为卡2
        return getLine1NumberForSubscriber(getSubIdForSlotId(slotId));
    }

    private int getSubIdForSlotId(int slotId) {
        int[] subIds = getSubId(slotId);
        if (subIds == null || subIds.length < 1 || subIds[0] < 0) {
            return -1;
        }
        Log.d("SystemUtils","getSubIdForSlotId = "+subIds[0]);
        return subIds[0];
    }
    private static int[] getSubId(int slotId) {
        Method declaredMethod;
        int[] subArr = null;
        try {
            declaredMethod = Class.forName("android.telephony.SubscriptionManager").getDeclaredMethod("getSubId",new Class[]{Integer.TYPE});
            declaredMethod.setAccessible(true);
            subArr = (int[]) declaredMethod.invoke(mSubscriptionManager,slotId);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            declaredMethod = null;
        } catch (IllegalArgumentException e2) {
            e2.printStackTrace();
            declaredMethod = null;
        } catch (NoSuchMethodException e3) {
            e3.printStackTrace();
            declaredMethod = null;
        } catch (ClassCastException e4) {
            e4.printStackTrace();
            declaredMethod = null;
        } catch (IllegalAccessException e5){
            e5.printStackTrace();
            declaredMethod = null;
        }catch (InvocationTargetException e6){
            e6.printStackTrace();
            declaredMethod = null;
        }
        if(declaredMethod == null) {
            subArr = null;
        }
        Log.d("SystemUtils","getSubId = "+subArr[0]);
        return subArr;
    }
    private String getLine1NumberForSubscriber(int subId){
        Method method;
        String status = null;
        try {
            method = mTelephonyManager.getClass().getMethod("getLine1NumberForSubscriber",int.class);
            method.setAccessible(true);
            status = String.valueOf(method.invoke(mTelephonyManager,subId));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        Log.d("SystemUtils","getLine1NumberForSubscriber = "+status);
        return status;
    }
    /**
     * 判断服务是否在运行
     * @param context
     * @param serviceName
     * @return
     * 服务名称为全路径 例如com.ghost.WidgetUpdateService
     */
    public static boolean isRunService(Context context,String serviceName) {
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceName.equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    /**
     * 判断服务是否在运行
     * @param mContext
     * @param service
     * @return
     * 服务名称为全路径 例如com.ghost.WidgetUpdateService
     */
    public static boolean isAccessibilitySettingsOn(Context mContext,final String service) {
        int accessibilityEnabled = 0;
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            Log.e("isAccessibilityOn", "Error finding setting, default accessibility to not found: "
                    + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
        if (accessibilityEnabled == 1) {
            Log.v("isAccessibilityOn", "***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(
                    mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();
                    Log.v("isAccessibilityOn", "-------------- > accessibilityService :: " + accessibilityService + " " + service);
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        Log.v("isAccessibilityOn", "We've found the correct setting - accessibility is switched on!");
                        return true;
                    }
                }
            }
        } else {
            Log.v("isAccessibilityOn", "***ACCESSIBILITY IS DISABLED***");
        }
        return false;
    }
}
